package softswitch.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import softswitch.model.Circuit;
import softswitch.model.Did;

@Stateless
public class DidDAO {

    @PersistenceContext(unitName = "persistence")
    private EntityManager em;

    public Did getById(Integer id) {
        return em.find(Did.class, id);
    }

    public Did save(Did did) {
        em.persist(did);
        return did;
    }

    public Did update(Did did) {
        return em.merge(did);
    }

    public void delete(Integer id) {
        em.remove(em.find(Did.class, id));
    }

    @SuppressWarnings("unchecked")
    public List<Did> list(int first, int max) {
        Query query = em.createQuery("SELECT e FROM Did e");
        if (max > 0) {
            query.setMaxResults(max);
        }
        if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();
    }

   // ------------------------------------------------------------------------------
    public Did getByNumber(Integer number) {
        Did result = null;
        Query query = em.createQuery("SELECT e FROM Did e WHERE e.number=:number");
        query.setParameter("number", number);
        try {
            result = (Did) query.getSingleResult();
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public List<Did> listByCircuit(Circuit circuit) {
        Query query = em.createQuery("SELECT e FROM Did e WHERE e.circuit=:circuit");
        query.setParameter("circuit", circuit);
        try {
            return query.getResultList();
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public Long listTotalItemsByCircuit(Circuit circuit) {
        Query query = em.createQuery("SELECT COUNT(e) FROM Did e WHERE e.circuit=:circuit");
        query.setParameter("circuit", circuit);
        try {
        	return (Long) query.getSingleResult();
        }
        catch (Exception e) {
            return null;
        }
    }

    public Double listTotalPriceByCircuit(Circuit circuit) {
        if (listTotalItemsByCircuit(circuit) == null) {
            return 0.0;
        }
        else {
        	Query query = em.createQuery("SELECT SUM(e.price) FROM Did e WHERE e.circuit=:circuit");
            query.setParameter("circuit", circuit);
            try {
            	return (Double) query.getSingleResult();
            }
            catch (Exception e) {
                return null;
            }
            
        }
       
    }

}
